package cn.grayrelese.response;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.core.env.Environment;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;

/***
 * 自定义相应
 */
public class CustomResponse {
    /**
     * 获取IP
     * @return
     */
    public static String getIp(){
        String ip = null;
        try {
            ip=  InetAddress.getLocalHost().getHostAddress();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return ip;
    }
    /**
     * 响应消息给页面
     * @param response
     * @param messages
     */
    public static void responseMessages(HttpServletResponse response, Map<String,String> messages) {
        response.setStatus(200);
        response.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            String json = new ObjectMapper().writeValueAsString(messages);
            outputStream.write(json.getBytes());
            outputStream.flush();
            outputStream.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
    public static Map<String,String> responseMessages(Environment env,String message) {
        Map<String,String> messages = new HashMap<>();
        messages.put("result",message);
        messages.put("port",env.getProperty("server.port"));
        messages.put("application-name",env.getProperty("spring.application.name"));
        messages.put("client-ip",getIp());
        messages.put("status","success");
        return messages;
    }

    /**
     * 响应服务信息给页面
     * @param message
     */
    public static void responseServiceMessages(HttpServletResponse response,Environment env,String message){
        Map<String,String> messages = new HashMap<>();
        messages.put("result",message);
        messages.put("port",env.getProperty("server.port"));
        messages.put("application-name",env.getProperty("spring.application.name"));
        messages.put("client-ip",getIp());
        messages.put("status","success");
        responseMessages(response,messages);
    }
}
